<?php
namespace Home\Controller;
use Think\Controller;
class DocController extends Controller {

	function example($id){
		header('type-content:text/html;charset:utf-8;');
		static $example_data = array(
			'startup'=>array('Index/index'),
			'startup_tags'=>array('Index/tags', 'Index/tags.html'),
			'controller_home'=>array('Hello/hello'),
			'model'=>array('Model/index', 'ArticleModel.class.php'),
			'adv_model'=>array('Advmodel/index', 'AdvArticleModel.class.php'),
			'template'=>array('Template/index', 'Template/index.html'),
		);

		$current = $example_data[$id];

		$output = '';

		foreach ($current as $key => $method) {
			$output.= $this->source($method);
		}
		exit($output);
	}

	function source($method){
		$position = $this->locationFile($method);

		return <<<code
<section>{$position['file']}</section>
<div class="highlight">
	<pre class="{$position['lang']}">
{$position['code']}
	</pre>
</div>
code;


	}

	function locationFile($method){
		$arr = explode('/', $method);
		$ctrl = $arr[0];
		$m = $arr[1];
		$ret = array();
		if(false !== stripos($method , '.html')){
			$ret['file'] = realpath(str_replace('.html.html', '.html', t($method)));
			$ret['code'] = file_get_contents($ret['file']);
			$ret['lang'] = 'html';
			$ret['code'] = htmlspecialchars($ret['code']);
		}else if(false != stripos($method, 'Model.class.php')){
			$ret['file'] = realpath(__DIR__."/../Model/{$method}");
			$ret['lang'] = 'php';
			$ret['code'] = file_get_contents($ret['file']);
			$ret['code'] = htmlspecialchars($ret['code']);
		}else{
			$ret['file'] = __DIR__."/{$ctrl}Controller.class.php";
			$search_str = "public function {$m}(";
			$file_arr = explode(PHP_EOL, file_get_contents($ret['file']));
			$startLine = 0;
			$maxLines = 25;

			foreach ($file_arr as $key => $line) {
				if( false !== stripos($line, $search_str)){
					$startLine = $key + 1;
					break;
				}
			}

			foreach (array_slice($file_arr, $startLine) as $key => $after_line) {
				if( false !== stripos($after_line, 'Public function')){
					$maxLines = $key + 1;
					break;
				}
			}

			$str = $this->renderSourceCode($ret['file'], $startLine, $maxLines);
			$ret['code'] = $str;
			$ret['lang'] = 'php';
		}
		return $ret;
	}

	function renderSourceCode($file, $startLine, $maxLines){
		$startLine--;	// adjust line number to 0-based from 1-based
		if($startLine<0 || ($lines=@file($file))===false || ($lineCount=count($lines))<=$startLine)
			return '';

		$beginLine = $startLine;
		$endLine = $startLine+$maxLines -1;

		$output = '';
		for($i = $beginLine;$i<=$endLine;++$i)
		{

			$output.= htmlspecialchars($lines[$i]);
		}
		return $output;
	}
}